#import "RegLoginViewController.h"
#import "PopUIManager.h"
#import "NetWorkManager.h"
#import "LogInOutManager.h"
#import "PhoneRegisterViewController.h"
#import "JsonUtil.h"
#import "YZRegInfoViewController.h"
#import "RequestServerAPI.h"
#import "ForgetPasswordViewController.h"

#import "MainViewCreater.h"
#import "IQKeyboardManager.h"
#import "UserDao.h"
#import "PhoneRegisterViewController.h"


@interface RegLoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *accountField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *forgetPwdButton;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;

@end

@implementation RegLoginViewController

-(void)viewWillAppear:(BOOL)animated
{
   self.navigationController.navigationBarHidden=YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customView];
    
    [[IQKeyboardManager sharedManager] setEnable:YES];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    
    textFieldActiveNums = 0;
    
    [_accountField addTarget:self action:@selector(textFieldDidChanged2:) forControlEvents:UIControlEventEditingChanged];
    
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    UIBezierPath *maskPath;
    maskPath = [UIBezierPath bezierPathWithRoundedRect:_phoneView.bounds
                                     byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)
                                           cornerRadii:CGSizeMake(5.0, 5.0)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = _phoneView.bounds;
    maskLayer.path = maskPath.CGPath;
    _phoneView.layer.mask = maskLayer;
    
    _passwordField.backgroundColor = [UIColor whiteColor];
    
    maskPath = [UIBezierPath bezierPathWithRoundedRect:_phoneView.bounds
                                     byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight)
                                           cornerRadii:CGSizeMake(5.0, 5.0)];
    
    maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = _passwordView.bounds;
    maskLayer.path = maskPath.CGPath;
    _passwordView.layer.mask = maskLayer;
    
    CALayer *TopBorder = [CALayer layer];
    TopBorder.frame = CGRectMake(0.0f, 0.0f, _passwordView.frame.size.width, 0.3f);
    TopBorder.backgroundColor = UIColorMake(235, 235, 235).CGColor;
    [_passwordView.layer addSublayer:TopBorder];
    
}

-(void)customView
{
    
    [_phoneView setNeedsLayout];
    [_phoneView layoutIfNeeded];
    [_passwordView setNeedsLayout];
    [_passwordView layoutIfNeeded];
    
    self.registerButton.layer.borderColor = [UIColorMake(255, 255, 255) CGColor];
    self.registerButton.layer.borderWidth = .25;
    self.registerButton.layer.cornerRadius = 4.0;
    
    self.loginButton.backgroundColor = UIColorMake(255, 63, 62);
    self.loginButton.layer.cornerRadius = 4.0;
    
    UIView *accountLeftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 45, 45)];
    accountLeftView.backgroundColor = [UIColor clearColor];
    UIImageView *accountLeftImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"account_left"]];
    [accountLeftImg setFrame:CGRectMake(13, 13, 16, 18)];
    [accountLeftView addSubview:accountLeftImg];
    _accountField.leftView = accountLeftView;
     _accountField.leftViewMode = UITextFieldViewModeAlways;
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"手机号" attributes:@{ NSForegroundColorAttributeName : DefaultPlaceHolderColor }];
    self.accountField.attributedPlaceholder = str;
    
    UIView *passwordLeftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 45, 45)];
    passwordLeftView.backgroundColor = [UIColor clearColor];
    UIImageView *passwordLeftImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"password_left"]];
    [passwordLeftImg setFrame:CGRectMake(13, 13, 16, 18)];
    [passwordLeftView addSubview:passwordLeftImg];
    _passwordField.leftView = passwordLeftView;
    _passwordField.leftViewMode = UITextFieldViewModeAlways;
    
    _phoneView.backgroundColor =[UIColor whiteColor];
   
    NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:@"密码" attributes:@{ NSForegroundColorAttributeName : DefaultPlaceHolderColor }];
    self.passwordField.attributedPlaceholder = str1;
    
    
}

-(void)textFieldDidChanged2:(UITextField *) textFiled{
    if (textFiled == _accountField) {
        if (textFiled.text.length > 11) {
            textFiled.text = [textFiled.text substringToIndex:11];
        }
    }
}

- (IBAction)login{
    [self.view endEditing:YES];   //关闭键盘
    debugLog(@"开始登陆");
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    
    if (_accountField.text.length == 0||_passwordField.text.length == 0){
        [popUIMgr popAlertView:self title:@"提示" message:@"账户或者密码不能为空" cancelButtonTitle:@"确定"];
        return;
    }
    
   
    NSString *account = _accountField.text;
    NSString *psw = _passwordField.text;
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:account, @"username",psw,@"pwd", nil]];
    
    
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_LOGIN data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) { //连接失败
            debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
            debugLog(@"服务器返回StateCode:%ld", (long)responseCode);
            
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                debugLog(@"数据字典: %@", dict);
                
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    //登录失败，弹窗提示
                    NSString *ret_msg;
                    switch ([[dict objectForKey:@"retCode"] integerValue]) {
                        case 1:{
                            ret_msg= @"Success Login";
                            NSMutableDictionary *dict_m = [[NSMutableDictionary alloc]initWithDictionary:dict];
                            [dict_m setObject:[dict objectForKey:@"nickname"] forKey:@"name"];
                            BOOL result = [[UserDao getInstance]saveUserData:dict_m];
                            NSArray *babyinfo = [dict objectForKey:@"babyinfo"];
                            
                            if(babyinfo!=nil && babyinfo.count>0){
                                for (NSDictionary* dicc in babyinfo) {
                                    [[BabyDao getInstance]saveBabyData:dicc];
                                }
                            }
                            if(result){
                                UIViewController *mainViewController = [[MainViewCreater getInstance]createMainView];
                               
                                UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                                window.rootViewController = mainViewController;
                                
                            }else{
                                [popUIMgr popAlertView:nil title:@"提示" message:@"登录失败" cancelButtonTitle:@"确定"];
                            }

                            break;
                        }case 2:{
                            ret_msg= @"用户名或密码不正确";
                            break;
                        }case 3:{
                            ret_msg= @"用户名与密码不匹配";
                            break;
                        }case 4:{
                            ret_msg= @"账号已经停用";
                            break;
                        }default:{
                            ret_msg= @"未知错误";
                            break;
                        }
                    }
                    if (![ret_msg isEqual:@"Success Login"]) {
                        [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
    
}

- (IBAction)forgetPassword{
    
    UIViewController *forgetPwdViewController = [[ForgetPasswordViewController alloc]init];
    [self.navigationController pushViewController:forgetPwdViewController animated:YES];
}

- (IBAction)parentRegister:(id)sender {
    /*
    YZRegInfoViewController *yzRegInfoViewController = [[YZRegInfoViewController alloc]initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:yzRegInfoViewController animated:YES];
     */
    PhoneRegisterViewController *phoneReg = [[PhoneRegisterViewController alloc]init];
    phoneReg.isRegister = YES;
    [self.navigationController pushViewController:phoneReg animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}

-(void)viewDidDisappear:(BOOL)animated{
    //清空输入框中的内容。
    _accountField.text = @"";
    _passwordField.text = @"";
}

@end
